package com.zhangkunhao.notes.web.servlet;

import com.alibaba.fastjson.JSON;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.entity.bo.PostPageBean;
import com.zhangkunhao.notes.entity.Do.User;
import com.zhangkunhao.notes.service.UserServiceImpl;
import com.zhangkunhao.notes.utils.SendEmailUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 用户的controller层
 *
 * @author 20642
 */
@WebServlet("/user/*")
public class UserServlet extends BaseDaoServlet {
    private UserServiceImpl userService = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        System.out.println("用户登录输入的验证码:" + checkCode);

        // 通过Session接收图片验证码
        HttpSession session = request.getSession();
        String checkCodeGenerate = (String) session.getAttribute("checkCodeGenerate");
        System.out.println("登录图片显示的验证码:" + checkCodeGenerate);

        Message<User> loginMessage = new Message<>(null, "验证码错误", 0);

        // 比对验证码
        if (checkCodeGenerate.equalsIgnoreCase(checkCode)) {
            // 接收用户数据,转为user对象
            User user = new User();
            user.setEmail(request.getParameter("email"));
            user.setPassword(request.getParameter("password"));
            // 调用service层
            loginMessage = userService.login(user);
        }

        //将登录用户的id、用户名存到session中
        if (loginMessage.getT() != null) {
            session.setAttribute("userId", loginMessage.getT().getId());
            session.setAttribute("userName", loginMessage.getT().getUserName());
        }

        // 转换为json数据并且写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(loginMessage));
    }


    public void forgetPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 通过Session接收sendEmailCode生成的验证码
        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute("emailCheckCode");
        System.out.println("邮箱生成的验证码：" + checkCode);

        Message<User> updatePassWordMessage = new Message<>(null, "邮箱的验证码错误，请再次获取验证码", 0);
        String jsonString = "";

        // 邮箱验证码校验
        String emailCheckCode = request.getParameter("emailCheckCode");

        //判断用户是否已经获取验证码
        if (checkCode == null) {
            System.out.println("用户没有点击获取验证码");
            updatePassWordMessage.setResult("您没有点击获取验证码");

            // 转换为json数据
            jsonString = JSON.toJSONString(updatePassWordMessage);

            // 写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(jsonString);
            return;
        }

        //校验验证码
        if (!checkCode.equals(emailCheckCode)) {
            System.out.println("用户输入的邮箱验证码错误:" + emailCheckCode);
            jsonString = JSON.toJSONString(updatePassWordMessage);

            //3.写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(jsonString);
            //必须return，否则方法不结束
            return;
        }

        //1.接收用户数据，转为user对象
        User user = new User();
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        System.out.println("修改密码的对象 " + user);

        //调用service层
        updatePassWordMessage = userService.forgetPassword(user);

        //将忘记密码的用户的id、用户名存到session中
        if (updatePassWordMessage.getT() != null) {
            session.setAttribute("userId", updatePassWordMessage.getT().getId());
            session.setAttribute("userName", updatePassWordMessage.getT().getUserName());
        }
        //转换为json数据
        jsonString = JSON.toJSONString(updatePassWordMessage);
        //3.写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(jsonString);
    }

    public void sendEmailCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //封装返回前端的数据
        Message<User> sendEmailCodeMessage = new Message<>(null, "邮箱验证码已经发送到2064272436@qq.com成功，请查收", 1);

        // 生成邮箱验证码并且存到session
        request.getSession().setAttribute("emailCheckCode", SendEmailUtil.sendEmailCheckCode());

        // 写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(sendEmailCodeMessage));
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取注册用户输入的验证码
        String checkCode = request.getParameter("checkCode2");
        System.out.println("用户注册输入的验证码:" + checkCode);

        // 通过Session接收图片验证码
        HttpSession session = request.getSession();
        String checkCodeGenerate = (String) session.getAttribute("checkCodeGenerate");
        System.out.println("注册的图片验证码:" + checkCodeGenerate);

        Message<User> registerMessage = new Message<>(null, "验证码错误", 0);

        // 比对验证码
        if (checkCodeGenerate.equalsIgnoreCase(checkCode)) {
            // 接收用户输入的数据，转为user对象
            User user = new User();
            user.setEmail(request.getParameter("email"));
            user.setPassword(request.getParameter("password"));
            System.out.println("注册的对象 " + user);

            // 调用service层
            registerMessage = userService.register(user);
        }

        //将注册用户的id、用户名存到session中
        if (registerMessage.getT() != null) {
            session.setAttribute("userId", registerMessage.getT().getId());
            session.setAttribute("userName", registerMessage.getT().getUserName());
        }

        // 转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(registerMessage));

    }

    public void showPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //调用service层,封装返回前端的对象
        PostPageBean postPageBean = userService.showPost();

        // 转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(postPageBean));
    }

    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.接收当前页码和每页展示条数，采用get请求方式
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        //2. 调用service分页查询
        PostPageBean postPageBean = userService.selectByPage(currentPage, pageSize);

        //3.转为json,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(postPageBean));
    }

    public void rankQuestionByLikesCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //调用service层,封装返回前端的对象
        PostPageBean postPageBean = userService.rankQuestionByLikesCount();

        // 转换为json数据，写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(postPageBean));
    }


    public void editProfile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        String params = request.getReader().readLine();

        //2.转为对象
        User user = JSON.parseObject(params, User.class);

        System.out.println(user + "控制层编辑个人信息的user");

        //3.调用service层,封装返回前端的对象
        Message<User> userMessage = userService.editProfile(user);

        //4.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userMessage));

    }

    public void updatePassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //2.调用service层,封装返回前端的对象
        Message<User> userMessage = userService.updatePassword(oldPassword, newPassword, userId);

        //3.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userMessage));
    }

    public void searchUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据,根据用户名搜索
        String myInterestedUser = new String(request.getParameter("myInterestedUser").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

        //2.调用service层,封装返回前端的对象
        PageBean<User> userPageBean = userService.searchUser(myInterestedUser);

        //3.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userPageBean));
    }


    public void showUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收数据
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //2.调用service
        Message<User> userMessage = userService.showUser(userId);

        //3.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userMessage));
    }

    public void editImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //接收数据
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //以json格式返回给前端
        String jsonString = "";

        // 上传文件保存的目录
        String uploadDirectory = "uploads";

        // 上传文件大小限制，5MB
        int maxFileSize = 1024 * 1024 * 5;

        // 内存中的最大文件大小，2MB
        int maxMemorySize = 1024 * 1024 * 2;

        String imageName = "";
        String imagePath = "";

        // 检查是否为文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            //response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不是文件上传请求")

            // 返回消息,转换为json数据
            jsonString = JSON.toJSONString(new Message<User>(null, "不是文件上传请求", 0));

            //3.写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(jsonString);
            System.out.println("不是文件上传请求");
            return;
        }

        // 创建一个文件上传处理工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 设置内存中的最大文件大小
        factory.setSizeThreshold(maxMemorySize);

        // 设置上传文件保存的目录
        File uploadDir = new File(getServletContext().getRealPath("") + "\\" + uploadDirectory);

        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        factory.setRepository(uploadDir);

        // 创建一个文件上传处理器
        ServletFileUpload uploader = new ServletFileUpload(factory);

        // 设置上传文件大小限制
        uploader.setFileSizeMax(maxFileSize);

        // 解析上传的文件
        List<FileItem> items = uploader.parseRequest(request);

        for (FileItem item : items) {
            if (!item.isFormField()) {
                // 如果是文件
                String fileName = new File(item.getName()).getName();
                String filePath = uploadDir + File.separator + fileName;
                System.out.println("filePath:" + filePath);
                imageName = filePath.substring(filePath.lastIndexOf('\\') + 1);
                imagePath = "http://localhost:8080/demo01/uploads/" + imageName;
                System.out.println("imagePath=" + imagePath);
                File uploadedFile = new File(filePath);
                item.write(uploadedFile);
            }
        }
//            response.getWriter().println("上传成功")

        //调用service
        Message<User> updatePictureMessage = userService.updatePicture(userId, imagePath);

        // 转换为json数据
        jsonString = JSON.toJSONString(updatePictureMessage);

        //3.写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(jsonString);
    }

    public void listUsers(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //调用service层,封装返回前端的对象
        PageBean<User> users = userService.listUsers();
        // 转换为json数据，写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(users));
    }

    public void banUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.get方式接收数据,乱码解决
        int banUserId = Integer.parseInt(new String(request.getParameter("banUserId").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));

        System.out.println("banUserId:" + banUserId);

        //2.调用service层,封装返回前端的对象
        Message<User> userMessage = userService.banUser(banUserId);

        //3.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userMessage));
    }

    public void cancelBanUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.get方式接收数据,乱码解决
        int cancelBanUserId = Integer.parseInt(new String(request.getParameter("cancelBanUserId").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));

        System.out.println("cancelBanUserId:" + cancelBanUserId);

        //2.调用service层,封装返回前端的对象
        Message<User> userMessage = userService.cancelBanUser(cancelBanUserId);

        //3.写数据，转为json
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(userMessage));
    }

}
